package com.favccxx.message.domain.message;

import lombok.extern.slf4j.Slf4j;
import org.apache.camel.CamelContext;
import org.apache.camel.Processor;
import org.apache.camel.Route;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.impl.DefaultCamelContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.List;

@Slf4j
@Service
public class MessageGateWay {

    private CamelState camelState = CamelState.INIT;
    private CamelContext camelContext = new DefaultCamelContext();

    @Autowired
    MessageService messageService;

    @PostConstruct
    private void init() {
        try {
            start();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    public void start() throws Exception {
        if (camelState != CamelState.RUNNING) {
            List<CamelRouter> camelRouters = messageService.getCamelRouters(camelContext);
            camelRouters.forEach(camelRouter -> {
                RouteBuilder routeBuilder = createRouteBuilder(camelRouter, camelRouter.getProcessor());
                try {
                    camelContext.addRoutes(routeBuilder);
                } catch (Exception e) {
                    log.error("!!!!!!  Message router start error! " + e.getMessage());
                    e.printStackTrace();
                }
            });
            camelContext.start();
            camelState = CamelState.RUNNING;
        }

    }

    public void stop() {
        if (camelState == CamelState.RUNNING) {
            List<Route> routes = camelContext.getRoutes();
            try {
                routes.forEach(x -> {
                    String routeId = x.getId();
                    try {
                        camelContext.removeRoute(routeId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                });
                camelContext.stop();
            } catch (Exception e) {
                log.error("stop error:" + e.getMessage(), e);
            }
            camelState = CamelState.STOP;
        }
    }

    private RouteBuilder createRouteBuilder(CamelRouter camelRouter, Processor processor) {
        String fromUri = camelRouter.getFrom();
        String toUri = camelRouter.getTo();
        if (log.isDebugEnabled()) {
            log.info("★★★★★ Create camel router from: " + fromUri + ", to: " + toUri);
        }

        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from(fromUri).convertBodyTo(String.class).process(processor).to(toUri).end();
            }
        };
    }

}
